package cn.wolfcode.web.Interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonRequest;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CherckPermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            //        强转成HandlerMethod对象,方便下面的获取方法的对象
            HandlerMethod method = (HandlerMethod) handler;
//        判断方法上是否有权限
            RequiredPermission methodAnnotation = method.getMethodAnnotation(RequiredPermission.class);
            if (methodAnnotation == null) {
                return true;
            }
            Employee employee = UserContext.getUser();
//        判断对象是不是管理员
            if (employee.isAdmin()) {
                return true;
            }
//       拿到登录员工的权限集合
            List<String> list = UserContext.getPermission();

            //拿到注解上的权限表达式
            String expression = methodAnnotation.expression();
//        判断该用户是否有权限
            for (String s : list) {
                if (s.equals(expression)) {
                    return true;
                }
            }
//        用户没有该权限,判断有没有@ResponseBody注解,返回两种情况
            ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
            if (responseBody == null) {
                //返回页面的控制器
                response.sendRedirect("/empnointerceptor");
            } else {
                //返回JSON
                response.setContentType("application/json;charset=utf-8");
                String string = JSON.toJSONString(new JsonRequest(false, "您没有权限访问"));
                response.getWriter().write(string);
            }
            return false;
        }

        return true;
    }
}
